<?php
/*
 * scrumbrella - Scrum board.
 *
 * Copyright (C) 2009  Gustavo N. Borgoni <gborgoni@voicemedia.com.ar>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

require_once("db.php");
require_once("db_schema.php");

/*! \brief return recordset with userlist
 *  \param $enabled 1 list only active users 0 list all
 *  \retval < 0 error 
 *  \retval = 0 no result
 *  \retval array with user lists
 */
function user_list($enabled=1)
{
	global $user_table, $accesslevel_table;

	$SQL = "SELECT usr.*, al.name AS access_level FROM ".$user_table." usr 
		LEFT JOIN ".$accesslevel_table." al on  usr.id_accesslevel = al.id_accesslevel
		WHERE enable=".$enabled;

	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while list users " . db_error_message($res));
		return -1;
	}

	if (db_numrows($res) > 0) {
		$user_count = 0;
		while ($row = db_fetchrow($res)) {
			foreach($row as $key => $value) {
				$users[$user_count][$key] = $value;
			}
			$user_count++;
		}
		db_freeresult($res);
		return $users;
	} else {
		return 0;
	}
}

/*! \brief check if an user exists
 *  \param $alias user alias
 *  \param $email user email
 *  \param $id != 0 to check if an other userID are registred with data ingresed
 *  \retval < 0 error
 *  \retval 1
 */
function user_exist($alias, $email, $id=0) 
{
	global $user_table;

	if ($id == 0) {
		$SQL = "SELECT * FROM ".$user_table." WHERE alias='".$alias."' and email='".$email."'";
	} else {
		$SQL = "SELECT * FROM ".$user_table." WHERE alias='".$alias."' and email='".$email."' and not id_user=".$id;
	}

	$res = db_query($SQL);
	if (db_error($res)) {
		logger_fatal("Error while checking if exits user '$name': " . db_error_message($res));
		return 0;
	}

	if (db_numrows($res) > 0) {
		$data = db_fetchrow($res);
		return $data['id_user'];
	} else {
		return 0;
	}
}

/*! \brief create a new user
 *  \param name the realname of user
 *  \param lastname the user lastname
 *  \param email user email
 *  \param alias alias for authentification
 *  \param password user password
 *  \retval 0 on success.
 *  \retval -1 on error.
 *  \retval -2 if user already exists.
 */
function user_add($name, $lastname, $email, $alias, $password, $access_level) 
{
	global $user_table;

	if (user_exist($alias, $email) > 0) {
		return -2;
	}

	$query =  "INSERT INTO $user_table (name, lastname, email, alias, password, id_accesslevel, enable) ".
			"VALUES ('$name','$lastname','$email','$alias', md5('$password'), {$access_level[0]}, 1)";

	$res = db_query($query);

	if (db_error($res)) {
		logger_fatal("Error while creating user '$name': " . db_error_message($res));
		return -1;
	}

	return 0;
}

/*! \brief modify an user
 *  \param name the realname of user
 *  \param lastname the user lastname
 *  \param mail user email
 *  \param alias alias for authentification
 *  \param id the userID to modify
 *  \retval 1 user modifiqued, 0 error
 */
function user_modify($name, $lastname, $mail, $alias, $id) 
{
	global $user_table;

	if (user_exist($alias, $email, $id) > 0) {
		return 0;
	}

	$SQL =  "UPDATE ".$user_table." SET name='".$name."', lastname='".$lastname.
			"',email='".$mail."', alias='".$alias."' WHERE id_user=".$id;
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while modifying user '$name': " . db_error_message($res));
		return 0;
	}

	return 1;
}

/*! \brief delete a user
 *  \param $id userID to delete
 *  \retval 1 user deleted, 0 error 
 */
function user_delete($id) 
{
	global $user_table;

	$SQL = "UPDATE ".$user_table." SET enabled=0 WHERE id_user=".$id;
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while deleting user '$id': " . db_error_message($res));
		return 0;
	}
	return 1;
}

/*! \brief change the password to an user
 *  \param $password user password
 *	\param $id user id
 *	\retval 1 password modified, 0 error
 */
function user_change_password($password, $id) 
{
	global $user_table;

	$SQL = "UPDATE ".$user_table." SET password='".md5($password)."' WHERE id_user=".$id;
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while modifying user password '$id': " . db_error_message($res));
		return 0;
	}

	return 1;
}

/*! \brief check the rol of an user on a project
 *  \param $user
 *  \param $project
 *  \retval < 0 Error
 *  \retval > 0 RoleID
 */
function user_role($user,$project)
{
	global $usr_role_table;

	$SQL = "SELECT * FROM ".$usr_role_table." WHERE id_user=".$user." and id_project=".$project;
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while check user role '$user': " . db_error_message($res));
		return -1;
	}

	if (db_numrows($res) > 0) {
		$data = db_fetchrow($res);
		return $data['id_role'];
	} else {
		return 0;
	}
}

/*! \brief check if auth data is true
 *  \param $user user alias
 *  \param $password user password
 *  \retval <= 0 Error
 *  \retval >0 ID user
 */
function user_login($user,$password)
{
	global $user_table;

	$SQL = "SELECT * FROM ".$user_table." WHERE alias='".$user."' AND password='".md5($password)."' AND enable=1";
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_fatal("Error while login user '$user' " . db_error_message($res));
		return -1;
	}

	if (db_numrows($res) > 0) {
		$data = db_fetchrow($res);
		return $data['id_user'];
	} else {
		return 0;
	}
}

/*! \brief logoff a user. */
function user_logoff()
{
	session_start();

	$_SESSION = Array();

	/* destroy the session cookie */
	if (isset($_COOKIE[session_name()])) {
		setcookie(session_name(), '', time()-42000, '/');
	}

	session_destroy();
}

/*! 
 * \brief Find a user based on a search string.
 * \param search String to find.
 * \retval An array with the results.
 */
function user_find($search = "")
{
	global $user_table;
	$users = Array();

	/* prepare the query. */

	$search = str_replace("  ", " ", $search);
	$query = "SELECT alias,lastname,id_user FROM $user_table WHERE enable = 1 AND ";
	$search_parts = explode(" ", $search);
	for ($i = 0; $i < count($search_parts); $i++) {
		if ($i > 0) {
			$query .= " AND ";
		}
		$query .= "(name LIKE '%{$search_parts[$i]}%' ";
		$query .= "OR lastname LIKE '%{$search_parts[$i]}%' ";
		$query .= "OR alias LIKE '%{$search_parts[$i]}%') ";
	}

	$query .= "ORDER BY name,lastname";

	$result = db_query($query);
	if (db_error($result)) {
		logger_error("Unable to find a user '$search'" . db_error_message($result));
		return NULL;
	}

	if (!db_numrows($result)) {
		return NULL;
	}

	$users_count = 0;
	while ($user = db_fetchrow($result)) {
		foreach ($user AS $key => $value) {
			$users[$users_count][$key] = $value;
		}
		$users_count++;
	}
	db_freeresult($result);

	return $users;
}

/*!
 * \brief Check alias availability.
 * \param alias Check if this alias exist.
 * \retval 1 if the alias exist.
 * \retval 0 if the alias is not being used.
 * \retval -1 on error.
 */
function user_alias_exist($alias)
{
	global $user_table;

	$query = "SELECT * FROM $user_table WHERE alias = '$alias' LIMIT 1";

	$result = db_query($query);
	if (db_error($result)) {
		logger_error("Unable to check if an alias exist. $query " . db_error_message($result));
		return -1;
	}

	if (db_numrows($result)) {
		return 1;
	}

	return 0;
}

/*!
 * \brief Get the user access level.
 * \param user_id Users ID.
 * \retval -1 on error.
 * \retval The users access level.
 */
function user_get_accesslevel($user_id)
{
	global $user_table;
	global $accesslevel_table;

	$query = "SELECT al.level level FROM $user_table u, $accesslevel_table al WHERE u.id_user = '$user_id' AND u.id_accesslevel = al.id_accesslevel";

	$result = db_query($query);
	if (db_error($result)) {
		logger_error("Unable to get access level for user '$user_id': " . db_error_message($result));
		return -1;
	}

	$data = db_fetchrow($result);
	return $data["level"];
}

/*!
 * \brief Check if an email address is being used for another user.
 * \param email Email address.
 * \retval -1 Error while checking for the email address. 
 * \retval 0 The email address is not being used.
 * \retval 1 The email address was already taken.
 */
function user_check_email($email)
{
	global $user_table;

	$query = "SELECT * FROM $user_table WHERE email = '$email' LIMIT 1";

	$result = db_query($query);

	if (db_error($result)) {
		logger_error("Unable to check email address '$email'" . db_error_message($result));
		return -1;
	}

	if (!db_numrows($result)) {
		/* the email address is not being used. */
		return 0;
	}

	/* the email address was already taken. */
	return 1;
}

/*! \brief return user list assigned to a project
 *  \param $project ID 
 *  \retval < 0 Error
 *  \retval Array list users
 */
function user_list_byproject($project) 
{
	global $user_role_table;
	global $user_table;
	global $role_table;

	$SQL = "SELECT a.id_user, b.name as username, b.lastname, c.name 
		FROM $user_role_table a
		LEFT JOIN $user_table b ON b.id_user = a.id_user 
		LEFT JOIN $role_table c ON c.id_role = a.id_role
		WHERE id_project=$project";
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_error("Unable to get project list" . db_error_message($res));
		return -1;
	}

	if (db_numrows($res) > 0) {
		$user_count = 0;
		while ($row = db_fetchrow($res)) {
			foreach ($row AS $key => $value) {
				$users[$user_count][$key] = $value;
			}
			$user_count++;
		}
		db_freeresult($res);

		return $users;
	} else {
		return 0;
	}
}

/*! \brief return the user name of an id
 *  \param $id user id
 *  \retval < 0 Error
 *  \retval string user name
 */
function user_name($id)
{
	global $user_table;

	$SQL = "SELECT * FROM $user_table WHERE id_user=$id";
	$res = db_query($SQL);

	if (db_error($res)) {
		logger_error(" Error when load user name " . db_error_message($res));
		return -1;
	}

	if (db_numrows($res) > 0) {
		while ($row = db_fetchrow($res)) {
			$name = $row['lastname']." ".$row['name'];
		}
		db_freeresult($res);

		return $name;
	} else {
		return 0;
	}
}
?>
